<template>
  <div>
    <div class="content search-panel">
      <el-col :span="10">
        <label>设备名称：</label>
        <el-autocomplete
          class="inline-input"
          v-model="deviceName"
          :fetch-suggestions="querySearch"
          placeholder="请输入内容"
          @select="handleSelect"
        ></el-autocomplete>
      </el-col>
      <el-col :span="7">
        <label>序列号：</label>
        <el-input v-model="serialNumber" placeholder="请输入内容" ></el-input>
      </el-col>
      <el-col :span="2">
        <el-button type="primary" @click="search">查询</el-button>
      </el-col>
      <el-col :span="2" class="margin-right-25">
        <el-button type="primary" @click="add">新建网关</el-button>
      </el-col>
      <el-col :span="2">
        <el-button type="primary" @click="deleteGateway">删除网关</el-button>
      </el-col>
    </div>

    <el-table
    :data="data"
    border
    style="width: 100%">
      <el-table-column
        label="设备名称"
        prop="deviceName">
      </el-table-column>
      <el-table-column
        label="型号"
        prop="deviceId">
      </el-table-column>
      <el-table-column
        label="序列号"
        prop="serialNumber">
      </el-table-column>
      <el-table-column
        label="状态"
        prop="condition">
      </el-table-column>
      <el-table-column
        label="上次联系时间">
        <template scope="scope">
          <span style="margin-left: 10px">{{ scope.row.lastContact | time }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="注册时间">
        <template scope="scope">
          <span style="margin-left: 10px">{{ scope.row.lastRegister | time }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作">
        <template scope="scope">
          <el-button size="small" @click="goToRealTimeData(scope.row.deviceId)">实时数据</el-button>
        </template>
      </el-table-column>
    </el-table>
  </div>
</template>
<script>
import _ from 'lodash'
import filtersMixin from '../mixins/filters'
import flattenDeep from 'lodash/flattenDeep'
import keyBy from 'lodash/keyBy'

export default {
  mixins: [filtersMixin],
  name: 'device',
  data () {
    return {
      deviceId: '',
      deviceName: '',
      serialNumber: '',
      data: [],
      serialNumberData: [],
      allDeviceIds: []
    }
  },
  computed: {
    user () {
      return JSON.parse(sessionStorage.getItem('user'))
    }
  },
  mounted: function () {
    this.requestData()
  },
  watch: {
    data () {
      this.serialNumberData = _.chain(this.data).map((item) => {
        return {
          value: item.name,
          id: item.id
        }
      }).uniq().value()
    }
  },
  methods: {
    querySearch (queryString, cb) {
      var serialNumberData = this.serialNumberData
      var results = queryString ? serialNumberData.filter(this.createFilter(queryString)) : serialNumberData
      // 调用 callback 返回建议列表的数据
      cb(results)
    },
    createFilter (queryString) {
      return (serialNumberData) => {
        return (serialNumberData.value.indexOf(queryString.toLowerCase()) === 0)
      }
    },
    handleSelect (item) {
      this.deviceId = item.id
    },
    requestData () {
      this.$http.get('/gateway/all?device_id=' + this.deviceId + '&device_name=' + this.deviceName + '&serial_number=' + this.serialNumber + '&company_id=' + this.user.id).then((res) => {
        var data = flattenDeep(res.data.objectList.map((item) => {
          return item.deviceList.map((i) => {
            return i
          })
        }))
        this.getDeviceInfo(data)
      })
    },
    getDeviceInfo (data) {
      // 请求设备信息，然后合并数据
      this.allDeviceIds = data.map((item) => { return item.deviceId })
      var req = this.allDeviceIds.map((id) => {
        return this.$http.get('/device/all?device_id=' + id)
      })
      Promise.all(req).then((datas) => {
        var d = datas.map((res) => {
          return res.data.deviceList[0]
        })
        var keyByData = keyBy(d, 'id')
        data.forEach((item) => {
          item.lastContact = keyByData[item.deviceId].lastContact
          item.lastRegister = keyByData[item.deviceId].lastRegister
        })
        this.data = data
      })
    },
    goToRealTimeData (deviceId) {
      this.$router.push({path: '/device/currentData/' + deviceId})
    },
    search () {
      this.requestData()
    },
    add () {
      // 新增
      this.$prompt('请输序列号', '新建网关', {
        confirmButtonText: '确定',
        cancelButtonText: '取消'
      }).then(({ value }) => {
        // 确定
        this.$http.post('/gateway/add', {companyId: this.user.id, serialNumber: value}).then((res) => {
          var data = flattenDeep(res.data.objectList.map((item) => {
            return item.deviceList.map((i) => {
              return i
            })
          }))
          this.getDeviceInfo(data)
        })
      }).catch(() => {
        // 取消
      })
    },
    deleteGateway () {
      // 删除
      this.$prompt('请输序列号', '删除网关', {
        confirmButtonText: '确定',
        cancelButtonText: '取消'
      }).then(({ value }) => {
        // 确定
        this.$http.post('/gateway/delete', {companyId: this.user.id, serialNumber: value}).then((res) => {
          var data = flattenDeep(res.data.objectList.map((item) => {
            return item.deviceList.map((i) => {
              return i
            })
          }))
          this.getDeviceInfo(data)
        })
      }).catch(() => {
        // 取消
      })
    }
  }
}
</script>
<style lang="stylus" scoped>
.content {
  padding: 20px;
}
.el-table {
  padding: 20px;
}
.search-panel {
  border: 1px solid #ccc;
  height: 100px;
  line-height: 100px;
  margin: 20px;
  padding: 0 20px;
}
.inline-input {
  width: 260px;
}
.el-col {
  display: inline-block;
}
.el-input {
  display: inline-block;
  width: 170px;
}
.margin-right-25 {
  margin-right: 25px;
}
</style>
